package com.controller;

import com.pojo.User;
import com.service.UserService;
import com.utils.ApiResult;
import com.utils.UserVo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author
 * @description user
 * @date 2022-12-19
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 新增
     *
     * @author
     * @date 2022/12/19
     **/
    @RequestMapping("/insert")
    public ApiResult insert(@RequestBody User user) {
        if (userService.load(user.getUsername()) != null) {
            return new ApiResult(500, "用户已存在", null);
        }
        userService.insert(user);
        return new ApiResult(200, "success", null);
    }


    /**
     * 更新
     *
     * @author
     * @date 2022/12/19
     **/
    @RequestMapping("/update")
    public ApiResult update(@RequestBody User user) {
        userService.update(user);
        return new ApiResult(200, "success", null);
    }

    /**
     * 更新
     *
     * @author
     * @date 2022/12/19
     **/
    @RequestMapping("/updatePassword")
    public ApiResult updatePassword(@RequestBody UserVo userVo) {
        // 通过用户名查询用户
        User dbUser = userService.load(userVo.getUsername());
        // 输入的旧密码和数据库中的密码进行比较，如果相同，更新密码
        if (userVo.getOldPassword().equals(dbUser.getPassword())) {
            if (userVo.getNewPassword().equals(dbUser.getPassword())) {
                return new ApiResult(500, "新密码不能与旧密码相同", null);
            } else {
                //如果新密码和旧密码不相同，更新密码
                dbUser.setPassword(userVo.getNewPassword());
                userService.update(dbUser);
                return new ApiResult(200, "修改成功", null);
            }
        } else {
            return new ApiResult(500, "旧密码错误", null);
        }
    }


    @RequestMapping("/login")
    public ApiResult login(@RequestBody User user) {
        User dbUser = userService.load(user.getUsername());
        if (dbUser == null) {
            return new ApiResult(400, "用户不存在", null);
        }
        if (!dbUser.getPassword().equals(user.getPassword())) {
            return new ApiResult(400, "密码错误", null);
        }
        return new ApiResult(200, "success", dbUser);
    }

}